<?php

namespace app\index\controller;

use app\index\Controller;
use think\Db;
use think\Validate;

/**
 *  app培训认证页面
 * Class TrainCertify
 * @package app\index\controller
 */
class TrainCertify extends Controller
{
    /**
     *  培训认证首页
     * @url /index/train_certify/index
     */
    public function index()
    {
        $data = input();
          $validate = new Validate([
              ['token','require','缺少token'],
          ]);
          //验证数据
          if(!$validate->check($data)){
              $msg['error_id']="1070003";
              $msg['message']=$validate->getError();
              return $this->error($msg);
          }
        $carArticle = Db::name('car_article')
                            ->where('status', 1)
                            ->field(['id','title','content','type'])
                            ->order('sort','asc')
                            ->select();
        $user = Db::name('driver')->where('user_id', UID)->find();
        $driverRank = []; // 司机等级
        $driverRank = [
            'driver_rank_id'=>0,
            'name' => '新手',
            'order_num' => empty($user['order_num']) ? 0 : $user['order_num'],
            'total_order_num' => Db::name('driver_rank')->where('id', 13)->value('order_num')
        ];
        if (!empty($user['driver_rank_id'])){
            $driverRankFind = Db::name('driver_rank')->where('id',$user['driver_rank_id'])->find();
            $totalOrderNum = $driverRankFind['order_num'];
            if ($user['driver_rank_id'] != 15){
                $superiorInfo = Db::name('driver_rank')->where('id','>',$user['driver_rank_id'])->order('id','asc')->find();
                $totalOrderNum = $superiorInfo['order_num'];
            }
            $driverRank = [
                'driver_rank_id'=>$user['driver_rank_id'],
                'name' =>$driverRankFind['name'],
                'order_num' => empty($user['order_num']) ? 0 : $user['order_num'],
                'total_order_num' => $totalOrderNum
            ];
        }
        // 加载课程
        $driverRankId = $driverRank['driver_rank_id'];
        $trainData = [];
        $driverReadTrainId = []; // 司机已读的培训课程
        static $isRead = 0;
        if ($driverRankId == 0){
            // 加载初级的培训资料
            $trainingMaterials = Db::name('training_materials')->where('rank_id', 13)
                                                                    ->where('isdelete', 0)
                                                                    ->order('id', 'asc')
                                                                    ->select();
            // 查询司机已读的培训资料
            $driverReadTrain = Db::name('training_materials_view')->where('user_id', UID)->field('training_materials_id')->select();
            if (!empty($driverReadTrain)){
                foreach ($driverReadTrain as $index2 => $item2) {
                    array_push($driverReadTrainId, $item2['training_materials_id']);
                }
            }
            if (!empty($trainingMaterials)){
                foreach ($trainingMaterials as $index => $trainingMaterial) {
                    $imgSrc  = Db::name('upload_file')->where('id', $trainingMaterial['video_img_id'])->value('url');
                    $trainingMaterials[$index]['video_img_id'] = get_host().$imgSrc;
                    if (!empty($driverReadTrainId) && in_array($trainingMaterial['id'], $driverReadTrainId)){
                        $trainingMaterials[$index]['is_read'] = 1;
                        $isRead++;
                    }else{
                        $trainingMaterials[$index]['is_read'] = 0;
                    }
                }
            }
            $trainData = $trainingMaterials;
        }elseif ($driverRankId == 13){
            // 加载中级的培训资料
            $trainingMaterials = Db::name('training_materials')->where('rank_id', 14)
                                                                    ->where('isdelete', 0)
                                                                    ->order('id', 'asc')
                                                                    ->select();
            // 查询司机已读的培训资料
            $driverReadTrain = Db::name('training_materials_view')->where('user_id', UID)->field('training_materials_id')->select();
            if (!empty($driverReadTrain)){
                foreach ($driverReadTrain as $index2 => $item2) {
                    array_push($driverReadTrainId, $item2['training_materials_id']);
                }
            }
            if (!empty($trainingMaterials)){
                foreach ($trainingMaterials as $index => $trainingMaterial) {
                    $imgSrc  = Db::name('upload_file')->where('id', $trainingMaterial['video_img_id'])->value('url');
                    $trainingMaterials[$index]['video_img_id'] = get_host().$imgSrc;
                    if (!empty($driverReadTrainId) && in_array($trainingMaterial['id'], $driverReadTrainId)){
                        $trainingMaterials[$index]['is_read'] = 1;
                        $isRead++;
                    }else{
                        $trainingMaterials[$index]['is_read'] = 0;
                    }
                }
            }
            $trainData = $trainingMaterials;
        }elseif ($driverRankId == 14){
            // 加载高级的培训资料
            $trainingMaterials = Db::name('training_materials')->where('rank_id', 15)
                                                                    ->where('isdelete', 0)
                                                                    ->order('id', 'asc')
                                                                    ->select();
            // 查询司机已读的培训资料
            $driverReadTrain = Db::name('training_materials_view')->where('user_id', UID)->field('training_materials_id')->select();
            if (!empty($driverReadTrain)){
                foreach ($driverReadTrain as $index2 => $item2) {
                    array_push($driverReadTrainId, $item2['training_materials_id']);
                }
            }
            if (!empty($trainingMaterials)){
                foreach ($trainingMaterials as $index => $trainingMaterial) {
                    $imgSrc  = Db::name('upload_file')->where('id', $trainingMaterial['video_img_id'])->value('url');
                    $trainingMaterials[$index]['video_img_id'] = get_host().$imgSrc;
                    if (!empty($driverReadTrainId) && in_array($trainingMaterial['id'], $driverReadTrainId)){
                        $trainingMaterials[$index]['is_read'] = 1;
                        $isRead++;
                    }else{
                        $trainingMaterials[$index]['is_read'] = 0;
                    }
                }
            }
            $trainData = $trainingMaterials;
        }else{
            // 高级不加载培训课程和订单完成量
        }
        // 总共加载多少门课程
        $curriculum = count($trainData);
        $is_read = $isRead;
        $isRead = 0;
        $this->view->assign([
            'car_article' => $carArticle,
            'token' => TOKEN,
            'driver_rank' => $driverRank,
            'train_data' => $trainData,
            'curriculum' => $curriculum,
            'is_read' => $is_read,
            'user_id' => UID
        ]);
        return $this->view->fetch('training_certification');
    }
    /**
     *  查看文本
     */
    public function viewText()
    {
        $data = input();
        if (empty($data['id']) || empty($data['token'])){
            $msg['error_id']="1100001";
            $msg['message']='缺少必要的参数';
            return $this->error($msg);
        }
        if ($data['id'] == 19 || $data['title'] == '等级介绍'){
            // 查询司机等级内容
            $ret = Db::name('driver_rank')->where('isdelete', 0)->select();
            // 查找司机的等级
            $driverRankId = Db::name('driver')->where('user_id', UID)->value('driver_rank_id');
            $this->view->assign('list', $ret);
            $this->view->assign('driver_rank_id', $driverRankId);
            return $this->view->fetch('lev');
        }elseif ($data['id'] == 2 || $data['title'] == '接单须知'){
            return $this->view->fetch('introduce');
        }elseif ($data['id'] == 21 || $data['title'] == '降级申诉'){
            $this->view->assign([
                'token' => TOKEN,
                'user_id' => UID,
            ]);
            return $this->view->fetch('demotion_appeal');
        }else{
            $list = Db::name('car_article')->where('id',$data['id'])->find();
            $this->view->assign([
                'list' => $list,
            ]);
            return $this->view->fetch('article');
        }

    }

    /**
     *  查看培训资料详情
     */
    public function courseDetail()
    {
        //获取数据
        $data = input();

        //验证规则
        $validate = new Validate([
            ['token','require','缺少token'],
            ['user_id','require','未指定用户'],
            ['training_materials_id','require','缺少培训资料id'],
        ]);

        //验证数据
        if(!$validate->check($data)){
            $msg['error_id']="1070001";
            $msg['message']=$validate->getError();
            return $this->error($msg);
        }

        //通过培训资料id到training_meterials表中获取数据
        $result = Db::name('training_materials') -> where('id',$data['training_materials_id']) -> find();
        $update['view_num'] = $result['view_num']+1;
        Db::name('training_materials') -> where('id',$data['training_materials_id']) -> update($update);
        $view['training_materials_id']=$data['training_materials_id'];
        $view['user_id']=$data['user_id'];
        $view['view_end']=NOW_TIME;
        $view['create_time']=NOW_TIME;
        $view['update_time']=NOW_TIME;
        $old_training_materials_view=Db::name('training_materials_view')->where(array('user_id'=>$data['user_id'],'training_materials_id'=>$data['training_materials_id']))->find();
        if(!$old_training_materials_view){
            Db::name('training_materials_view')->insert($view);
        }

        if($result['video_img_id']){
            $result['video_img_url']=get_host().get_default_img($result['video_img_id'],true);
        }else{
            $result['video_img_url']="/upload/img/5b0ab1a7bbd7ae17.png";
        }
        $msg['data'] = $result;
        $this->view->assign('list', $result);
        return $this->view->fetch('train_course');
//        if($result==true){
//            $msg['message'] = '获取成功';
//            return $this->success($msg);
//        }else{
//            $msg['message'] = '获取失败';
//            $msg['error_id'] = '1070002';
//            return $this->error($msg);
//        }
    }
}
